<template>
    <div id="load-message" class="flex-center">
        <div class="container">
            <div class="top-content flex-center">
                <div class="top-list s-14" :class="status==='loading'?'active':'noactive'" @click="status='loading'">
                    正在下载
                </div>
                <div class="top-list s-14" :class="status==='complete'?'active':'noactive'" @click="status='complete'">
                    下载记录
                </div>
            </div>
            <div class="handel flex-between">
                <div class="s-14 t-color-n" v-show="status == 'loading'">剩余任务：{{tableData.length}}</div>
                <div class="s-14 t-color-n" v-show="status == 'complete'">已完成任务：{{completeData.length}} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;失败任务数：{{failCount}}个</div>
                <div v-show="status == 'complete'" @click="clearDownLoad" class="s-14 t-color-n pointer">清除下载记录</div>
                <div class="flex-center" v-show="status == 'loading'">
                    <div class="pointer handel-btn flex-center" style="margin-right: 13px;" @click="batchStop">
                        <img src="./img/stop.png" alt="">
                        <a class="pointer s-14 t-color-n">暂停</a>
                    </div>
                    <div class="pointer handel-btn flex-center" style="margin-right: 13px;" @click="batchStart">
                        <img src="./img/start.png" alt="">
                        <a class="pointer s-14 t-color-n">开始</a>
                    </div>
                    <div class="pointer handel-btn flex-center" style="margin-right: 13px;" @click="cancelLoad">
                        <img src="./img/cancel.png" alt="" style="width: 10px;height: 10px">
                        <a class="pointer s-14 t-color-n">取消</a>
                    </div>
                </div>
            </div>
            <div v-show="status == 'loading'">
                <el-table   :data="tableData" :border="false" stripe style="width: 100%" height="525" :header-cell-style="headerStyle" :cell-style="cellStyle">
                    <el-table-column width="45" align="center">
                        <template slot="header" slot-scope="scope">
                            <el-checkbox v-model="allChecked" :disabled="tableData.length === 0" @change="changeAll"></el-checkbox>
                        </template>
                        <template slot-scope="scope">
                            <!-- 隐试修改vuex不合法但暂不作改动 -->
                            <el-checkbox v-model="scope.row.checked" @change="(val)=>changeRow(val,scope.row)"></el-checkbox>
                        </template>
                    </el-table-column>
                    <el-table-column label="课程名" width="180">
                        <template slot-scope="scope">
                            <div class="flex-start">
                                <img src="./img/file.png" alt="" class="file">
                                <el-tooltip effect="dark" :content="scope.row.name" placement="top-start" v-if="scope.row.name.length>11">
                                    <span style="font-weight: 600;" class="s-14 line-over-ellipsis">{{scope.row.name}}</span>
                                </el-tooltip>
                                <span style="font-weight: 600;" class="s-14 line-over-ellipsis" v-else>{{scope.row.name}}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="教材版本" width="120">
                        <template slot-scope="scope">
                            <div class="flex-start">
                                <span style="font-weight: 400; font-size: 12px">{{scope.row.publisher}}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="课本" width="110">
                        <template slot-scope="scope">
                            <div class="flex-start">
                                <span style="font-weight: 400; font-size: 12px">{{scope.row.book}}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" style="border-left: 1px solid rgba(236,236,236,1)">
                        <template slot-scope="scope">
                            <div v-if="scope.row.status === 2">
                                <el-progress :percentage="scope.row.progress.progressVal > 100 ? 100 : scope.row.progress.progressVal" :format="() => format(scope.row)"></el-progress>
                            </div>

                            <span style="color:#606266" class="s-12 t-color-c" v-else-if="scope.row.status === 3">已暂停</span>
                            <span style="color:#F66C6C" class="s-12 t-color-c" v-else-if="scope.row.status === 4">下载失败...</span>
                            <span v-else-if="scope.row.status === 0" class="s-12 t-color-c">初始化成功....</span>
                            <span v-else-if="scope.row.status === 1" class="s-12 t-color-c">初始化失败....</span>
                            <span class="s-12 t-color-c" v-else-if="scope.row.status === 5  ">初始化中....</span>
                            <span class="s-12 t-color-c" v-else-if="scope.row.status === 6 ">正在等待....</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="50">
                        <template slot-scope="scope">
                            <img src="./img/start.png" class="pointer" v-if="scope.row.status === 3" @click="start(scope.row)">
                            <img src="./img/stop.png" class="pointer" v-if="[0,2,5,6].includes(scope.row.status)" @click="stop(scope.row)">
                            <img @click="refresh(scope.row)" class="pointer" src="./img/refresh.png" v-if="scope.row.status === 1 || scope.row.status === 4">
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-show="status == 'complete'">
                <el-table :data="completeData" :border="false" stripe style="width: 100%" height="525" :header-cell-style="headerStyle">
                    <!-- <el-table-column width="20" style="visibility: hidden;"></el-table-column> -->
                    <el-table-column label="课程名" max-width="180">
                        <template slot-scope="scope">
                            <div class="flex-start">
                                <img src="./img/file.png" alt="" class="file">
                                <el-tooltip effect="dark" :content="scope.row.lessonName" placement="top-start" v-if="scope.row.lessonName.length>7">
                                    <span style="font-weight: 600;" class="s-14 line-over-ellipsis">{{scope.row.lessonName}}</span>
                                </el-tooltip>
                                <span style="font-weight: 600;" class="s-14 line-over-ellipsis" v-else>{{scope.row.lessonName}}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="教材版本" max-width="180">
                        <template slot-scope="scope">
                            <div class="flex-start">
                                <span style="font-weight: 400; font-size: 12px">{{scope.row.publisherName}}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="课本" max-width="60">
                        <template slot-scope="scope">
                            <div class="flex-start">
                                <span style="font-weight: 400; font-size: 12px">{{scope.row.bookName}}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" width="110" style="border-left: 1px solid rgba(236,236,236,1)">
                        <template slot-scope="scope">
                            <div v-if="scope.row.status !== '部分成功'">
                                <img style="position:relative;top:-4px" src="./img/arrows.png" alt="">
                                <span class="s-12 t-color-n">{{scope.row.status}}</span>
                            </div>
                            <div v-else class="pointer" style="display:flex;align-items:center;" @click="reDownloadLesson(scope.row)">
                                <img style="margin-right:5px" class="pointer" src="./img/refresh.png">
                                <span class="s-12 t-color-w pointer">{{scope.row.status}}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="完成时间" align="center" max-width="200" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <span class="s-12 t-colo-n ">
                                {{scope.row.endTime}}
                            </span>
                            <!-- <el-tooltip effect="dark" :content="scope.row.endTime" placement="bottom-end">

                            </el-tooltip> -->
                        </template>
                    </el-table-column>
                    <el-table-column label="跳转" align="center" width="50">
                        <template slot-scope="scope">
                            <img src="./img/redirect.png" class="pointer" @click="redirect(scope.row)">
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <img @click="close" src="../../../.../../assets/img/home/close.png" class="close pointer">
        </div>
    </div>
</template>

<script>
import { DownloadCenter } from "../../../../../../static/lib/downloader/DownloadCenter";
import { StringUtil } from "../../../../../../static/utils/StringUtil";
import { SqlLibBook } from "../../../../../../static/lib/sqlite/service/SqlLibBook";
import { SqlLib } from "../../../../../../static/lib/sqlite/SqlLib";
import { mapState,mapMutations} from "vuex"
import { SqlLibUser } from "../../../../../../static/lib/sqlite/service/SqlLibUser";
import bus from '../../../assets/js/bus'
import store from '@/content/store/index.js'
export default {
    data() {
        return {
            multipleSelection: [],
            status: 'loading',
            allChecked: false,
            selectRow:[],
            // clickCancel:false,
        }
    },
    created() { },
    computed: {
        // selectRow() {
        //     let selectRow = [];
        //     this.tableData.forEach(data => {
        //         if (data.checked) {
        //             selectRow.push(data.id);
        //         }
        //     });
        //     return selectRow
        // },
        failCount() {
            let count = 0;
            this.completeData.forEach(data => {
                if (data.status === '部分成功') {
                    count++;
                }
            });
            return count
        },
        ...mapState({
            tableData:state => state.loadingLessonSet,
            completeData:state => state.completedBook
        })
    },
    watch: {
        tableData(newval,oldval){
            let arry = []
            newval.forEach(data => {
                if (data.checked) {
                    arry.push(data.id);
                }
            });
            this.selectRow = arry
        }
    },
    // mounted(){
    //     this.tableData.forEach(item => {
    //         this.changeLoadingStatus({id:item.id,checked:false})
    //     })
    // },
    beforeDestroy() {
        this.tableData.forEach(item => {
            this.changeLoadingStatus({id:item.id,checked:false})
        })
    },
    methods: {
        ...mapMutations(['addLoadingLesson','changeLoadingStatus','addCompletedBook','clearDownLoadCenter']),
        stop(row) {
            DownloadCenter.getInstance().pauseDownloadCenter([row.id]);
            this.changeLoadingStatus({id:row.id,checked:false})
        },
        start(row) {
            DownloadCenter.getInstance().resumeDownloader([row.id],true);
            this.changeLoadingStatus({id:row.id,checked:false})
        },
        batchStop() {
            if (this.selectRow.length === 0) {
                this.$message.warning("没有选中的课时！");
            }
            if (!this.allChecked) {//部分选中
                DownloadCenter.getInstance().pauseDownloadCenter(this.selectRow);
            } else {//全部选中
                DownloadCenter.getInstance().pauseDownloadCenter(this.selectRow, false,true);
            }
            this.selectRow.forEach((item) => {
                this.changeLoadingStatus({id:item,checked:false})
            })
            this.selectRow = []
            if(this.allChecked){
                this.allChecked = false
            }
        },
        batchStart() {
            if (this.selectRow.length === 0) {
                this.$message.warning("没有选中的课时！");
            }
            DownloadCenter.getInstance().resumeDownloader(this.selectRow,false);
            this.selectRow.forEach((item) => {
                this.changeLoadingStatus({id:item,checked:false})
            })
            this.selectRow = []
            if(this.allChecked){
                this.allChecked = false
            }
        },
        cancelLoad() {
            if (this.selectRow.length === 0) {
                this.$message.warning("没有选中的课时！");
            }
            DownloadCenter.getInstance().cancelDownLoad(this.selectRow);
            this.selectRow.forEach((item) => {
                this.changeLoadingStatus({id:item,checked:false})
            })
            this.selectRow = []
            if(this.allChecked){
                this.allChecked = false
            }
        },
        clearDownLoad(){
            if (store.state.completedBook) {
                store.state.completedBook.forEach(index=>{
                    this.$store.commit('removeCompletedBook',index.lessonId)//移除vuex中已下载课程记录
                })
                store.state.completedBook= []
            } 
            let sqlLib = SqlLib.getInstance(window.$DBDIR)
            const user = SqlLibUser.queryCurrentUser(sqlLib)
            SqlLibBook.deleteAllDownloadedLessonByUserId(SqlLib.getInstance(window.$DBDIR),user.id)
            this.$message.success('清除成功')
        },
        refresh(row) {
            DownloadCenter.getInstance().resumeDownloader([row.id]);
        },
        format(row) {
            return StringUtil.format("{0}%（{1}KB/s）", row.progress.progressVal ? row.progress.progressVal : 0, row.progress.speed ? row.progress.speed : 0);
        },
        cellStyle(cell) {
            if (cell.row.status === 4 || cell.row.status === 1) {
                return 'background-color:rgba(246,108,108,0.1)'
            }
            if (this.selectRow.includes(cell.row.id)) {
                return 'background-color:rgba(72,148,255,0.1)'
            }
            return (cell.rowIndex % 2) === 0 ? 'background-color:#fff' : 'background-color:#FAFAFA'
        },
        headerStyle(cell) {
            if (cell.columnIndex > 1) {
                return 'border-left: 1px solid rgba(236,236,236,1) ;background-color: #FAFAFA '
            }
            return 'background-color: #FAFAFA '
        },
        close() {
            this.$emit('closeDowmMessage')
        },
        changeRow(val,row) {
            if (!val) {
                this.allChecked = false;
                this.selectRow.includes(row.id) && this.selectRow.splice(this.selectRow.indexOf(row.id),1)
            } else {
                this.selectRow.push(row.id)
                let result = true;
                this.tableData.forEach(row => {
                    if (!row.checked) {
                        result = false;
                    }
                });
                if (!result) {
                    this.allChecked = false;
                } else {
                    this.allChecked = true;
                }
            }
        },
        changeAll(val) {
            if (val) {
                this.tableData.forEach(item => {
                    this.changeLoadingStatus({id:item.id,checked:true})
                })
            } else {
                this.tableData.forEach(item => {
                     this.changeLoadingStatus({id:item.id,checked:false})
                })
            }
        },
        reDownloadLesson(row) {
            if (row.lessonId) {
                let _this = this;
                let sqlLib = SqlLib.getInstance(window.$DBDIR);
                let downloadParams = [];
                let currentDownIds = DownloadCenter.getInstance().getCurrentDownloadingLesson();

                if (!currentDownIds.includes(row.lessonId)) {
                    let tableNames = SqlLibBook.queryChaAndBookNameByLessonId(sqlLib, row.lessonId);
                    let downloadParam = {
                        SetDownloadId: row.lessonId,
                        DownloaderInfo: { lessonName: tableNames.lessonName, bookName: tableNames.bookName, publisherName: tableNames.publisherName },
                        ActionStatus: "1" //动作的状态：0 - 下载；1 - 更新；2 - 同步
                    }
                    downloadParams.push(downloadParam);
                }
                if (downloadParams.length > 0) {
                    DownloadCenter.getInstance().initFailedRecordLoad(downloadParams);
                    // let curIndex = -1;
                    // _this.completeData.forEach((download, index) => {
                    //     if (download.lessonId === row.lessonId) {
                    //         curIndex = index;
                    //     }
                    // });
                    // if (curIndex !== -1) {//代表存在
                    //     _this.completeData.splice(curIndex, 1);
                    // }
                }
            }
        },
        redirect(row) {
            console.log(row);
            let sqlLib = SqlLib.getInstance(window.$DBDIR);
            let result = SqlLibBook.queryBookAndCharpterByLessonId(sqlLib, row.lessonId);
            let currentUser = SqlLibUser.queryCurrentUser(sqlLib);
            currentUser.lessonId = result.lessonId;
            currentUser.bookId = result.bookId;
            console.log(currentUser);
            // return
            sqlLib.updateOrInsertObjectById(currentUser);
            if (this.$route.name !== "home") {//当前页面不是home页
                this.$router.push({ name: 'home', params: { lessonId: result.lessonId, bookId: result.bookId } })
            } else {
                bus.$emit("refreshHome")
            }
            this.close();
        }
    }
}
</script>

<style lang="scss">
#load-message {
    .list-enter-active,
    .list-leave-active {
    transition: all 1s ease;
    }
    .list-enter-from,
    .list-leave-to {
    opacity: 0;
    transform: translateX(30px);
    }
    position: absolute;
    background-color: rgba(0, 0, 0, 0.6);
    z-index: 2022;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    .container {
        width: 62.5vw;
        max-width: 1170px;
        height: 71.111vh;
        max-height: 835px;
        background: rgba(255, 255, 255, 1);
        border-radius: 8px;
        position: relative;
        .top-content {
            width: 100%;
            height: 7.111vh;
            max-height: 85px;
            background: rgba(244, 244, 244, 1);
            border-radius: 8px;
        }
        .handel {
            height: 5.556vh;
            max-height: 65px;
            padding: 0 20px;
        }
        .handel-btn {
            width: 108px;
            height: 4vh;
            background: rgba(255, 255, 255, 1);
            border: 1px solid rgba(221, 222, 231, 1);
            border-radius: 8px;
            img {
                width: 14px;
                height: 14px;
                margin-right: 6px;
            }
        }
        .top-list {
            width: 108px;
            height: 4vh;
            line-height: 4vh;
            text-align: center;
            border: 1px solid rgba(72, 147, 255, 1);
            &:nth-child(1) {
                border-radius: 8px 0px 0px 8px;
            }
            &:nth-child(2) {
                border-radius: 0px 8px 8px 0px;
            }
        }
        .active {
            background: rgba(72, 148, 255, 1);
            color: #fff;
        }
        .noactive {
            color: #4893ff;
        }
        .table-container {
            height: 525px;
            width: 100%;
            overflow: auto;
        }
        .complete-table-container {
            overflow: auto;
        }
        img {
            width: 14px;
            height: 14px;
        }
        .close {
            position: absolute;
            right: 10px;
            top: 10px;
            width: 15px;
            height: 15px;
        }
        .file {
            height: 20px;
            width: 16px;
            margin-right: 12px;
        }
        .el-progress__text {
            margin-left: 25px;
        }
        .el-progress-bar {
            width: 183px;
        }
        .el-table td,
        .el-table th.is-leaf {
            border: none;
        }
        .el-table::before {
            display: none;
        }
    }
}
</style>
